<?php

namespace app\api\controller;

use app\BaseController;
use app\common\model\Users;
use think\facade\Request;

class Base extends BaseController
{

    //用户的id
    public $user_id = 0;
    public $user = [];
    protected $default_token = "aca83cb99bb62fd24cd6077f165a7175";
    protected $site_url;

    protected function initialize()
    {
        parent::initialize();

        $this->site_url = SITE_URL;
        $no_verify = array(
            'get_app_download_url',
            'login',
            'weixin_login',
            'bind_mobile',
            'register',
            'forget_pwd',
            'weather',
            'index',
            'index_goods',
            'test',
            'search',
            'sub_search',
            'empty_search',
            'goods_cate',
            'cate_goods'
            ,
            'goods_detail',
            'get_essay',
            'get_code',
            'get_login',
            'wx_mobile',
            'get_region'
        );
        $new_arr = array_map('strtolower', $no_verify);
        $act_name = strtolower(ACTION_NAME);
        //不需要验证的界面 如公告详情是要让界面显示的
        $not_verify = ['qrcode', 'index_goods', 'index', 'goods_detail', 'goods_cate', 'cate_goods', 'loginbyphone', 'essay_detail', 'protocol_detail', 'ry_protocol_detail', 'tabbar', 'config', 'officialconfig', 'get_pick_list', 'get_foster_goods_category', 'get_foster_goods'];
        //需要进行md5验证才能提交 如修改信息 删除地址等场景
        $data = input('post.');
        $user_id = input('user_id/d');
        $info = Request::header();
        if (!in_array($act_name, $not_verify)) {
            if (in_array($act_name, $new_arr)) {
                if ($user_id) {
                    $user = Users::find($user_id);
                    $this->user_id = $user_id;
                    if (empty($user)) {
                        exit(json_encode(['code' => 0, 'msg' => '用户不存在', 'error' => 1]));
                    }
                    $this->default_token = $user['token'];
                    $this->user = $user;
                }
            } else {
                if (empty($user_id)) {
                    exit(json_encode(['code' => 401, 'msg' => '请先登录~', 'error' => 2]));
                }
                $user = Users::find($user_id);
                $this->user_id = $user_id;
                if (empty($user)) {
                    exit(json_encode(['code' => 0, 'msg' => '用户不存在', 'error' => 3]));
                }
                $this->default_token = $user['token'];
                $this->user = $user;
            }
            if ($this->default_token != $info['token']) {
                exit(json_encode(['code' => 401, 'msg' => '请先登录~', 'error' => 4]));
            }
            if (empty($data['sign'])) {
                exit(json_encode(['code' => 0, 'msg' => 'sign不能为空', 'error' => 5]));
            }
            if ($data['cart']) {
                unset($data['cart']);
            }
            //请求端提交的sign值
            $sign_md5 = $data['sign'];
            foreach ($data as $k1 => $v1) {
                if (is_array($v1)) {
                    unset($data[$k1]);
                }
            }
            unset($data['sign']);
            ksort($data);
            $sign = '';
            foreach ($data as $key => $val) {
                if ($val != '') {
                    $sign .= $key . $val;
                }
            }
            $sign_prefix = config('app.sign_prefix');
            if ($sign) {
                $encode = urlencode($sign . $sign_prefix . $this->default_token . $sign_prefix);
                $last_sign = md5($encode);
            } else {
                $encode = urlencode($sign_prefix . $this->default_token . $sign_prefix);
                $last_sign = md5($encode);
            }
            if ($last_sign != $sign_md5) {
                exit(json_encode(['code' => 0, 'msg' => '非法操作', 'error' => 6]));
            }
        }
    }

    //生成Token
    protected function getToken($username)
    {
        //获取前台传来的用户账号
        $admin = $username;
        $time = time();
        //设置token过期时间为一天
        $end_time = time() + 86400;
        $info = $admin . '.' . $time . '.' . $end_time;
        //根据以上信息信息生成签名（密钥为 huangfu)
        $signature = hash_hmac('md5', $info, 'huangfu');
        //最后将这两部分拼接起来，得到最终的Token字符串
        return $info . '.' . $signature;
    }

    //验证Token
    protected function checkToken($token)
    {
        if (empty($token)) {
            return 401;
        }
        //以.分割token为数组
        $explode = explode('.', $token);
        $user = get_user_info($this->user_id);
        if (!empty($explode[0]) && !empty($explode[1]) && !empty($explode[2]) && !empty($explode[3])) {
            //信息部分
            $info = $explode[0] . '.' . $explode[1] . '.' . $explode[2];
            //正确的签名
            $true_signature = hash_hmac('md5', $info, 'huangfu');
            if ($explode[0] != $user['mobile']) {
                $status = 401;
            } else {
                if (time() > (int)$explode[2]) {
                    $status = 204;
                } else {
                    if ($true_signature == $explode[3]) {
                        $status = 200;
                    } else {
                        $status = 401;
                    }
                }
            }
        } else {
            $status = 401;
        }
        return $status;
    }
}
